package com.zengqingfa.thread.demo7;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @fileName: UnsafeBuyTickets
 * @author: zengqf3
 * @date: 2020-10-7 18:22
 * @description:
 */
public class BuyTickets {

    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        Thread t1 = new Thread(ticket, "A");
        Thread t2 = new Thread(ticket, "B");
        Thread t3 = new Thread(ticket, "C");
        t1.start();
        t2.start();
        t3.start();

    }

}

class Ticket implements Runnable {

    private int ticketNums = 10;

    //定义锁
    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            try {
                lock.lock();
                if (ticketNums <= 0) {
                    return;
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "拿到" + ticketNums--);
            } finally {
                lock.unlock();
            }
        }

    }
}